package net.huafv.authoritycontrol.security;

import cn.hutool.json.JSONUtil;
import jakarta.servlet.ServletOutputStream;
import net.huafv.authoritycontrol.common.lang.Result;
import net.huafv.authoritycontrol.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Component
public class LoginSuccessHandler implements AuthenticationSuccessHandler {

	@Autowired
	JwtUtil jwtUtil;

	@Override
	public void onAuthenticationSuccess(jakarta.servlet.http.HttpServletRequest request, jakarta.servlet.http.HttpServletResponse response, Authentication authentication) throws IOException, jakarta.servlet.ServletException {
		response.setContentType("application/json;charset=UTF-8");
		ServletOutputStream outputStream = response.getOutputStream();
		UserDetails userDetails = (UserDetails) authentication.getPrincipal();

		System.out.println("onAuthenticationSuccess");

		String jwt = "";

		Map<String,Object> map = new HashMap<>();

		map.put("sub", "fly");
		map.put("username",userDetails.getUsername());

		Date nowDate = new Date();
		Date expireDate = new Date(nowDate.getTime() + 1000 * 7);

		// 生成jwt，并放置到请求头中
		jwt = JwtUtil.createToken("huafv", map, expireDate);

		Map<String,String> m = new HashMap<>();
		m.put("token",jwt);

		Result result = Result.success(200, "操作成功",m);
		outputStream.write(JSONUtil.toJsonStr(result).getBytes(StandardCharsets.UTF_8));

		outputStream.flush();
		outputStream.close();
	}
}
